import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useSettingsStore = defineStore('settings', () => {
  // 状态
  const appSettings = ref({
    darkMode: false,
    notificationsEnabled: true,
    autoSyncEnabled: true
  });

  const fitnessGoals = ref({
    type: 'lose_weight', // lose_weight, gain_muscle, maintain, improve_fitness
    calorieGoal: 2000,
    weeklyWorkoutGoal: 3
  });

  // 从本地存储加载数据
  const loadSettings = () => {
    try {
      const savedSettings = localStorage.getItem('appSettings');
      const savedGoals = localStorage.getItem('fitnessGoals');

      if (savedSettings) appSettings.value = JSON.parse(savedSettings);
      if (savedGoals) fitnessGoals.value = JSON.parse(savedGoals);
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  };

  // 保存数据到本地存储
  const saveSettings = () => {
    try {
      localStorage.setItem('appSettings', JSON.stringify(appSettings.value));
      localStorage.setItem('fitnessGoals', JSON.stringify(fitnessGoals.value));
    } catch (error) {
      console.error('Failed to save settings:', error);
    }
  };

  // 初始化
  loadSettings();

  // 动作
  const updateAppSettings = (newSettings) => {
    appSettings.value = {
      ...appSettings.value,
      ...newSettings
    };
    saveSettings();
  };

  const saveFitnessGoals = (goals) => {
    fitnessGoals.value = {
      ...fitnessGoals.value,
      ...goals
    };
    saveSettings();
  };

  const getSettings = () => appSettings.value;
  const getFitnessGoals = () => fitnessGoals.value;

  const toggleDarkMode = () => {
    appSettings.value.darkMode = !appSettings.value.darkMode;
    saveSettings();
    return appSettings.value.darkMode;
  };

  const clearSettings = () => {
    appSettings.value = {
      darkMode: false,
      notificationsEnabled: true,
      autoSyncEnabled: true
    };
    fitnessGoals.value = {
      type: 'lose_weight',
      calorieGoal: 2000,
      weeklyWorkoutGoal: 3
    };
    saveSettings();
  };

  return {
    appSettings,
    fitnessGoals,
    loadSettings,
    saveSettings,
    updateAppSettings,
    saveFitnessGoals,
    getSettings,
    getFitnessGoals,
    toggleDarkMode,
    clearSettings
  };
});